<?php
/**
 * source:http://blog.lockphp.com/yii-work/yii-ar-log-auto.html
 * 
 * @author Elwin
 *
 */
abstract class LogActiveRecordBehavior extends CActiveRecordBehavior{
	private $_oldattributes = array();

	public function afterFind($event)
	{
		//记录旧数据
		$attributes = $this->Owner->getAttributes();
		$this->setOldAttributes($attributes);
	}
	
	public function beforeSave($event)
	{
		//删除缓存
		$key = $this->Owner->getCacheKey();
		Yii::app()->cache->delete($key);
	}
	
	public function afterSave($event)
	{
		// new attributes
		$newattributes = $this->Owner->getAttributes();
		$oldattributes = $this->getOldAttributes();
	
		// 获得该操作资源的名称 如 ‘产品’、‘新闻’
		$resource_name = $this->Owner->getResourceName();
		// 获得该操作资源的类名
		$modelclass = $this->Owner->getModelClass();
		// 获得该操作资源的主键
		$pk = $this->Owner->getPrimaryKey();
	
		//后台log
		$log = new Log();
		//LOG 一级大类
		$type = $resource_name.'管理';
		//LOG 二级分类
		if($this->Owner->isNewRecord)
		{
			$category = '添加'.$resource_name;
		}
		else
		{
			$category = '修改'.$resource_name;
		}
	
		// AR中的deleteMark()方法
		if($newattributes['is_delete'] == 1 AND $oldattributes['is_delete'] == 0)
		{
			$category = '删除'.$resource_name;
		}
	
		$model_attributes_old = CJSON::encode($oldattributes);
		$model_attributes_new = CJSON::encode($newattributes);
	
		$info = array(
				'log_type'=>$type,
				'log_category'=>$category,
				'log_description'=>$description,
				'log_model'=>$modelclass,
				'log_model_pk'=>$pk,
				'log_model_attributes_old'=>$model_attributes_old,
				'log_model_attributes_new'=>$model_attributes_new,
		);
		$log->mylog($info);
	}
	
	//旧数据
	public function getOldAttributes()
	{
		return $this->_oldattributes;
	}
	
	public function setOldAttributes($value)
	{
		$this->_oldattributes=$value;
	}
}

// http://www.yiiframework.com/wiki/9/how-to-log-changes-of-activerecords/

?>